import Vue from 'vue'
import Router from 'vue-router'
import ShopLogin from '../components/ShopLogin.vue'
import ShopHome from '../components/ShopHome.vue'
import ShopWelcome from '../components/ShopWelcome.vue'
import Users from '../components/user/Users.vue'
import Report from '../components/report/Report.vue'
Vue.use(Router)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: ShopLogin },
  // welcome作为home的子路由，故写在children中
  {
    path: '/home',
    component: ShopHome,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: ShopWelcome },
      { path: '/users', component: Users },
      { path: '/reports', component: Report }
    ]
  }
]
const router = new Router({ routes })

// 挂载路由导航守卫
// 如果用户没有登录，但是直接通过url访问特定页面，需要重新导航到登录页面
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 从哪个路径来的
  // next 一个函数，表示放行
  // next() 放行  next('/login') 强制跳转

  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router
